/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package main

import (
	"flag"
	"fmt"
	"io/ioutil"

	"gitee.com/WisdomClassroom/cli/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gopkg.in/yaml.v2"
	"gorm.io/gorm"
)

type QuestionAndBinds struct {
	Question models.Question
}

func main() {
	core.PublicFlag(BuildTag, BuildGo, BuildTime)
	var dataFilePath string
	flag.StringVar(&dataFilePath, "data-file-path", "", "path to data file")
	flag.Parse()

	if core.FlagHelp {
		fmt.Println("Rename genQuestions.template.yaml to genQuestions.private.yaml and can be placed anywhere, then put questions in it")
		flag.Usage()
		return
	}
	if core.FlagVersion {
		core.PublicVersion()
		return
	}
	if core.FlagUseSqlite == core.FlagUsePG {
		core.PrintPromptWarning("You must choose one database\n\n")
		flag.Usage()
		return
	}

	var err error
	if core.FlagUseSqlite {
	} else if core.FlagUsePG {
	}

	bytes, err := ioutil.ReadFile(dataFilePath)
	if err != nil {
		core.PrintPromptWarning(fmt.Sprintf("Read file error\n%v", err))
		return
	}
	var questionsAndBinds []QuestionAndBinds
	err = yaml.Unmarshal(bytes, &questionsAndBinds)
	if err != nil {
		core.PrintPromptWarning(err.Error())
		return
	}

	err = glb.DB.Transaction(func(tx *gorm.DB) error {
		for _, questionAndBinds := range questionsAndBinds {
			questionAndBinds.Question.UUID = core.GenUUID()
			err := tx.Create(&questionAndBinds.Question).Error
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		core.PrintPromptWarning(fmt.Sprintf("Write database error, no data written\n%v", err))
		return
	}

	core.PrintPromptInfo("All questions created successfully")
}
